# coding=utf-8
import re
import pandas as pd
import os
from optparse import OptionParser
import random
import shutil
from getMp3 import getMP3
from ps import PlaySound
import threading
import traceback

cList = []  # 翻译列表
eList = []  # 单词列表
wList = []  # 权重增加列表
wList2 = []  # 权重减少列表
reList = [0, 0]  # 结果统计列表
tempList = []  # 备份列表
dataDic1 = {}  # 英译汉字典
dataDic2 = {}  # 汉译英字典
dataDicString = {}  # 分词词典


def playWord(word):
    getMP3(word)
    t = threading.Thread(target=PlaySound, args=(word,))
    t.start()


def resetWeight(data, filename):
    shutil.copyfile(filename, filename + '.bak')
    for i in range(0, len(data)):
        data.loc[i, '权重'] = 0  # 重置权重
    data.to_excel(filename, index=False)
    print("重置完成！")


def randTimes(data, weight):
    if weight.__eq__("F"):
        random.shuffle(cList)
    else:
        for i in range(0, len(data)):
            if int(data['权重'][i]) > 0:
                num = 5 if 5 < int(data['权重'][i]) else int(data['权重'][i])
                for j in range(0, num):
                    cList.append(data['翻译'][i])
        random.shuffle(cList)


def randTimes2(data, weight):
    if weight.__eq__("F"):
        random.shuffle(eList)
    else:
        for i in range(0, len(data)):
            if int(data['权重'][i]) > 0:
                num = 5 if 5 < int(data['权重'][i]) else int(data['权重'][i])
                for j in range(0, num):
                    eList.append(data['词汇'][i])
        random.shuffle(eList)


def removeWord(word, weight):
    if weight.__eq__("F"):
        cList.remove(word)
    else:
        for item in cList[:]:
            if item == word:
                cList.remove(word)


def removeWord2(word, weight):
    if weight.__eq__("F"):
        eList.remove(word)
    else:
        for item in eList[:]:
            if item == word:
                eList.remove(word)


def addWeight(data, filename):
    # print(wList)
    # print(tempList)
    for i in wList:
        # print(tempList.index(i)+2)
        id = tempList.index(i)
        if data.loc[id, '权重'] < 5:
            data.loc[id, '权重'] += 1  # 增加权重
    for i in wList2:
        # print(tempList.index(i)+2)
        id = tempList.index(i)
        if data.loc[id, '权重'] > 0:
            data.loc[id, '权重'] -= 1  # 减少权重
    data.to_excel(filename, index=False)


def c2e(data, times, weight, aw, filename):  # 汉译英
    input("按下回车开始汉译英默写: [Enter]")
    randTimes(data, weight)
    reList[0] = times
    reList[1] = 0
    for i in range(0, times):
        word = cList[0]
        print(str(i + 1) + ".翻译: " + word)
        playWord(dataDic2[word])
        myWord = input("单词: ")
        if (myWord in dataDic1) and (dataDic1[myWord].__eq__(word)):
            print('正确√！' + dataDicString[myWord] + "\n")
            if aw.__eq__('T'):
                wList2.append(dataDic2[word])
        else:
            print('错误×！正确答案: ' + dataDic2[word] + " " + dataDicString[dataDic2[word]] + "\n")
            reList[1] += 1
            if aw.__eq__('T'):
                wList.append(dataDic2[word])
        removeWord(word, weight)
    percent = round(((reList[0] - reList[1]) / reList[0]), 2) * 100
    print("默写结束！ 总共词数:" + str(reList[0]) + ", 错误词数:" + str(reList[1]) + ",正确率:" + str(percent) + "%")
    if aw.__eq__('T'):
        shutil.copyfile(filename, filename + '.bak')
        addWeight(data, filename)


def e2c(data, times, weight, aw):  # 英译汉
    input("按下回车开始英译汉默写: [Enter]")
    randTimes2(data, weight)
    reList[0] = times
    reList[1] = 0
    for i in range(0, times):
        word = eList[0]
        print(str(i + 1) + ".词汇: " + word)
        myWord = input("翻译: ")
        searchList = re.findall(myWord, dataDic1[word])
        if (len(searchList) > 0) and (myWord != ""):
            print('正确√！完整翻译: ' + dataDic1[word] + " " + dataDicString[word] + "\n")
        else:
            print('错误×！正确答案: ' + dataDic1[word] + " " + dataDicString[word] + "\n")
            reList[1] += 1
        removeWord2(word, weight)
    percent = round(((reList[0] - reList[1]) / reList[0]), 2) * 100
    print("默写结束！ 总共词数:" + str(reList[0]) + ", 错误词数:" + str(reList[1]) + ",正确率:" + str(percent) + "%")


def getLine(data, lines):
    # print(lines)
    # 130,140 取130行到140行
    if re.match(r'^\d.+,\d.+$', lines) is not None:
        lineList = lines.split(',')
        lineList = [int(x) - 2 for x in lineList]
        lineRange = range(int(lineList[0]), int(lineList[1]) + 1)
        data = data.loc[list(lineRange)]
        return data
    # 10 取前10行
    if re.match(r'^\d.*$', lines) is not None:
        lineRange = range(int(lines))
        data = data.loc[lineRange]
        return data
    # -10 取倒数10行
    if re.match(r'^-\d.*$', lines) is not None:
        lines = lines.strip("-")
        lineRange = range(len(data) - int(lines), len(data))
        data = data.loc[lineRange]
        return data


def readFile(data):  # 读取dataFrame内容
    for i, row in data.iterrows():  # 遍历dataFrane
        dataDic1[data['词汇'][i]] = data['翻译'][i]
        dataDic2[data['翻译'][i]] = data['词汇'][i]
        dataDicString[data['词汇'][i]] = "[过去式: " + data['过去式'][i] + ", 过去分词: " + data['过去分词'][i] + ", 现在分词: " + \
                                       data['现在分词'][i] + "]"
        eList.append(data['词汇'][i])
        cList.append(data['翻译'][i])
    for j in eList:
        tempList.append(j)


def run(wDic):
    # print(wDic)
    # filename,writeType,times,lines,onlyWeight,weight,addWeight,resetWeight
    filename = wDic["-f"]
    writeType = wDic["-t"]
    times = int(wDic["-n"])
    lines = wDic["-l"]
    if wDic["-o"] != "":
        onlyWeight = int(wDic["-o"])
    else:
        onlyWeight = None
    weight = wDic["-w"]
    addWeight = wDic["-a"]
    reset = wDic["-r"]
    try:
        data = pd.read_excel(filename)  # 从指定xlsx读取单词DataFrame
        if lines != "" and lines is not None:
            if len(data) < int(lines):
                lines = len(data)
            data = getLine(data, lines)
            weight = "F"  # 不能和Weight模式同时使用！
            addWeight = "F"
        if onlyWeight is not None and onlyWeight > 0:
            data = data.loc[data['权重'] >= int(onlyWeight)]  # 筛选出大于某权重的所有单词
            weight = "F"  # onlyWeight不能和Weight模式同时使用！
            addWeight = "F"
        if times > len(data) or times == 0:
            times = len(data)
        readFile(data)
        # print(dataDic)
        # print(eList)
        if reset.__eq__('T') and reset == 'T':
            resetWeight(data, filename)
            return
            # os._exit(0)
        if writeType.__eq__("c2e"):
            c2e(data, times, weight, addWeight, filename)
        else:
            e2c(data, times, weight, addWeight)
    except Exception as e:
        print(e)
        traceback.print_exc()
        # pass

